// pages/agent/plugins/feedback/create/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bgImage: '',
    // 所属街道列表
    feedbackAreaList: [],
    arrayDisabled: true,
    multiIndex: [],
    multiArray: [],
    tempFilePaths: [],
    uploadImg: [],
    info: {
      location: '',
      // 选择的问题类别
      type_id: '',
      description: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    options.pageName && (wx.setNavigationBarTitle({
      title: options.pageName,
    }))
    console.log('=========')
    console.log(app.globalData.config)
    this.setData({
      bgImage: app.globalData.config['agentPlugins']['workOrder'] && app.globalData.config['agentPlugins']['workOrder']['bgImage'] || ''
    })
  },

  // 获取所属街道列表
  loadFeedbackAreaList() {
    var that = this;
    var params = {
      point_url: app.server.agentApi.getFeedbackAreaList
    }
    app.server.getConnect(params).then(function(res) {
      var temp = [
        [],
        []
      ];
      temp[0] = res.data;
      temp[1] = res.data[0]['chartData'];
      that.setData({
        arrayDisabled: false,
        feedbackAreaList: res.data,
        multiArray: temp
      });
      that.loadFeedbackTypeList();
    })
  },

  // 获取问题类别
  loadFeedbackTypeList() {
    var that = this;
    var params = {
      point_url: app.server.agentApi.getFeedbackTypeList
    }
    app.server.getConnect(params).then(function(res) {
      that.setData({
        feedbackTypeList: res.data
      })
    })
  },

  bindMultiPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var temp = e.detail.value;
    if(temp[0]===null){
      temp[0]=0;
    }
    this.setData({
      multiIndex: temp
    })
  },

  bindMultiPickerColumnChange: function(e) {
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiIndex: this.data.multiIndex
    };
    if (e.detail.column == 0) {
      var temp = [
        [],
        []
      ];
      temp[0] = this.data.feedbackAreaList;
      temp[1] = this.data.feedbackAreaList[e.detail.value]['chartData'] || [];
      data.multiArray = temp;
    }
    data.multiIndex[e.detail.column] = e.detail.value;
    // console.log(data);
    this.setData(data);
  },

  // 选择地点
  bindSelectAdress() {
    var that = this;
    wx.chooseLocation({
      success(res) {
        console.log(res);
        that.setData({
          ['info.location']: res.address
        })
      }
    });
  },

  // 选择问题类别
  bindSelectFeedbackType(e) {
    // console.log(e);
    this.setData({
      ['info.type_id']: e.currentTarget.id
    })
  },

  // 详情输入
  bindTextAreaBlur: function(e) {
    console.log(e.detail.value);
    this.setData({
      ['info.description']: e.detail.value
    })
  },

  //上传图片
  upload: function() {
    var that = this;
    var pics = this.data.tempFilePaths;
    wx.chooseImage({
      count: 3 - pics.length,
      success: function(res) {
        console.log(res);
        var outSize = [];
        for (var i = 0; i < res.tempFiles.length; i++) {
          if (res.tempFiles[i].size > 4 * 1024 * 1024) {
            outSize.push(i + 1);
          }
        }
        if (outSize.length > 0) {
          app.showConfirm('提示', '图片大小须在4M以内，第' + outSize.join('，') + '张不符合要求', false);
          return;
        }
        pics.push.apply(pics, res.tempFilePaths);
        that.setData({
          tempFilePaths: pics
        })
      },
    })
  },

  //浏览图片
  preview: function(e) {
    var index = e.currentTarget.dataset.index;
    var url = this.data.tempFilePaths
    wx.previewImage({
      urls: url,
      current: url[index]
    })
  },

  //删除图片
  deleteImg: function(e) {
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var temp = this.data.tempFilePaths;
    temp.splice(index, 1);
    this.setData({
      tempFilePaths: temp
    })
  },

  // 提交工单
  createWorkList: function() {
    var that = this;
    if(this.data.multiIndex.length===0){
      app.showConfirm('提示', '请选择所属街道', false);
    }else if(!this.data.info.location){
      app.showConfirm('提示', '请选择具体位置', false);
    }else if(this.data.info.type_id===''){
      app.showConfirm('提示', '请选择问题类别', false);
    }else if(this.data.info.description===''){
      app.showConfirm('提示', '请输入详细情况', false);
    }else{
      that.data.uploadImg = [];
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      if (that.data.tempFilePaths != null && that.data.tempFilePaths != '' && that.data.tempFilePaths.length != 0) {
        for (var i = 0; i < that.data.tempFilePaths.length; i++) {
          if (that.data.tempFilePaths[i].indexOf('wxfile://') > -1 || that.data.tempFilePaths[i].indexOf('http://tmp') > -1) {
            app.server.uploadImage(that.data.tempFilePaths[i], {
              work_order_type: 2
            }).then(function (res) {
              that.data.uploadImg.push(res.data.url)
              if (that.data.uploadImg.length == that.data.tempFilePaths.length) {
                that.submitFeedback();
              }
            }, function (res) {
              app.showConfirm('提示', '图片上传失败，请重试', false);
              wx.hideLoading();
            });
          }
        }
      } else{
        that.submitFeedback();
      }
    }
  },

  submitFeedback(){
    var data = {
      point_url: app.server.agentApi.submitFeedback,
      father_id: this.data.feedbackAreaList[this.data.multiIndex[0]]['id'],
      son_id: this.data.feedbackAreaList[this.data.multiIndex[0]]['chartData']?this.data.feedbackAreaList[this.data.multiIndex[0]]['chartData'][this.data.multiIndex[1]]['id']:0,
      description: this.data.info.description,
      pic_list: JSON.stringify(this.data.uploadImg),
      address: this.data.info.location,
      type_id: this.data.info.type_id
    };
    app.server.getConnect(data).then(function (res) {
      console.log(res);
      app.showConfirm('提示', '工单提交成功', false, function () {
        wx.navigateBack();
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    app.pageOnloadInit(this, app);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.multiIndex.length<=0){
      this.loadFeedbackAreaList();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    app.pageOnloadInit(this, app);
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})